/*
 * Zenlayer.com Inc.
 * Copyright (c) 2014-2020 All Rights Reserved.
 */
package com.shen.core.utils;

import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.ObjectUtils;

import java.io.IOException;
import java.io.StringWriter;

/**
 * @author yangshen
 * @version $ Id: JacksonUtil.java, v 0.1  yangshen Exp $
 * @date 2019-11-29 15:10:03
 */

public class JacksonUtil {
    private static final ObjectMapper mapper = new ObjectMapper();

    static {
        mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
    }

    public static String bean2Json(Object obj) throws IOException {
        StringWriter sw = new StringWriter();
        JsonGenerator gen = new JsonFactory().createGenerator(sw);
        mapper.writeValue(gen, obj);
        gen.close();
        return sw.toString();
    }

    public static <T> T json2Bean(String jsonStr, Class<T> objClass) throws IOException {
        return mapper.readValue(jsonStr, objClass);
    }

    public static <T> T json2BeanByR(String jsonStr, TypeReference<T> objClass) throws IOException {
        return mapper.readValue(jsonStr, objClass);
    }

    public static <T> String bean2JsonToString(T object) {
        try {
            return mapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return ObjectUtils.identityToString(object);
    }

    public static <T, S> T beanCopy(S original, Class<T> change) throws IOException {
        String originalString = bean2Json(original);
        return json2Bean(originalString, change);
    }

    public static <T, S> T beanListCopy(S original, TypeReference<T> objClass) throws IOException {
        String originalString = bean2Json(original);
        return json2BeanByR(originalString, objClass);
    }

}